import { useCallback } from 'react';

interface CacheOptions {
  expire?: number; // 过期时间，单位毫秒
}

export function useCache() {
  const setCache = useCallback((key: string, data: any, options?: CacheOptions) => {
    const cacheData = {
      data,
      timestamp: Date.now(),
      expire: options?.expire,
    };
    localStorage.setItem(key, JSON.stringify(cacheData));
  }, []);

  const getCache = useCallback((key: string) => {
    const cached = localStorage.getItem(key);
    if (!cached) return null;

    const { data, timestamp, expire } = JSON.parse(cached);
    if (expire && Date.now() - timestamp > expire) {
      localStorage.removeItem(key);
      return null;
    }

    return data;
  }, []);

  return { setCache, getCache };
}